package view;

import java.awt.KeyboardFocusManager;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

import controle.AtalhosListener;


public class AbrirArquivo {

	private static JFileChooser chooser;

	
	public static String[] abrir() {
		String s[] = new String[2];
		try {		
			if (chooser == null) {
				chooser = new JFileChooser();
				chooser.setFileFilter(new FileFilter() {
					
					@Override
					public String getDescription() {
						return ".txt";
					}
					
					@Override
					public boolean accept(File arq) {
						return arq.getName().endsWith(".txt") || arq.isDirectory();
					}
				});
			}
			
			KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(AtalhosListener.getInstancia());
			if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
				File arq = chooser.getSelectedFile();
				String texto = "";
				BufferedReader in = new BufferedReader(new FileReader(arq));
				String linha;
				while ((linha = in.readLine()) != null) {
					texto += linha + "\n";
				}	
				s[0] = arq.getAbsolutePath();
				s[1] = texto;
				in.close();
				KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(AtalhosListener.getInstancia());
				return s;
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
		KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(AtalhosListener.getInstancia());
		return null;
	}
}
